/**
 * @File   : PageCtr.tsx
 * @Author : dtysky (dtysky@outlook.com)
 * @Link   : dtysky.moe
 * @Date   : 2022/9/27 23:50:18
 */
import * as React from 'react';
import {KeyboardEvent} from "react";
import {Icon, Slider} from 'hana-ui';

import css from '../styles/reader.module.scss';
import {TBookType} from '../../interfaces/protocols';

interface IPageCtrProps {
  color: string;
  start: number;
  max: number;
  current: number;
  blurPrev: number;
  blurNext: number;
  onJump(progress: number): void;
  onPre(): void;
  onNext(): void;
}

export function PageCtr(props: IPageCtrProps) {
  const prevRef = React.useRef(null);
  const nextRef = React.useRef(null);
  const wrapper = React.useRef(null);
  if (!props.max) {
    return null;
  }
  const handleKeyboardEvent = (event: KeyboardEvent<HTMLDivElement>) => {
    console.log('pagectrl process event ', event)
    if (event.key === 'ArrowLeft') {
      props.onPre();
    } else if (event.key === 'ArrowRight') {
      props.onNext();
    }
  };
  React.useEffect(() => {
    if (prevRef && prevRef.current) {
      prevRef.current.click();
      wrapper.current.focus();
    }
  }, [props.blurPrev])
  React.useEffect(() => {
    if (nextRef && nextRef.current) {
      nextRef.current.click();
      wrapper.current.focus();
    }

  }, [props.blurNext])


  // @ts-ignore
  return (
    <div tabIndex={0} className={css.pageCtr} ref={wrapper} onKeyDown={handleKeyboardEvent}>
      <div className={css.pageCtrPre} onClick={props.onPre} ref={prevRef}/>
      <div className={css.pageCtrNext} onClick={props.onNext} ref={nextRef}/>
      <div className={css.pageCtrSlider}>
        <Slider
          style={{marginTop: 0}}
          size='small'
          color={props.color}
          icon={<Icon type='clover' color={props.color} />}
          showValue={false}
          value={props.current}
          min={props.start}
          max={props.max}
          //@todo throttle
          onChange={val => props.onJump(val)}
        />
      </div>
    </div>
  )
}
